<template>
    <div class="w_h_100">
        <div class="box">
            <div class="inlet">系统管理 > 权限管理 ><span class="size">用户管理</span></div>
            <myform :fields="fields" :model="values" class="m_t_10" :options="options">
                <template v-slot:button>
                    <el-button @click="resetting">重置</el-button>
                    <el-button type="primary" :icon="Search" @click="searchFor">搜索</el-button>
                </template>
            </myform>
        </div>
        <div class="mytable m_t_10 ">
            <div class="d_f j_c_s_b a_i_c">
                <h4>用户明细列表</h4>
                <el-button type="primary" :icon="Plus" @click="adduser" v-hasPerm="'addAccount'">新建用户</el-button>
            </div>
            <mytable :fields="tableFields" width="250" :isSelection="false" ref="tableRef" :values="values"
                api="empListByPage" class="m_t_10">
                <template v-slot:isBiz="{ row }">{{ row.isBiz == 0 ? '是' : '否' }}</template>
                <template v-slot:status="{ row }">
                    <el-switch v-model="row.status" inline-prompt active-text="开" inactive-text="关" :active-value="0"
                        :inactive-value="1" @change="changeSwitch(row.id, row.status)"
                        style="--el-switch-on-color:#13ce66; " />
                </template>
                <template v-slot:operation="{ row }">
                    <div class="d_f j_c_s_b">
                        <span class="edit" @click="detail(row)">查看详情</span>
                        <span class="edit" @click="resetPassword(row)" v-hasPerm="'resetAccount'">重置密码</span>
                        <span class="edit" @click="edit(row)" v-hasPerm="'editAccount'">编辑</span>
                        <span class="error" @click="deleteOut(row.id)" v-hasPerm="'deleteAccount'">删除</span>
                    </div>
                </template>
            </mytable>
        </div>
        <el-drawer v-model="show" :title="title" size="600px" direction="rtl" :before-close="handleClose">
            <div class="userForm">
                <myform :fields="addFields" :options="options" @handleSelect="handleSelect" ref="ruleFrom"
                    :model="model" :inline="true" labelPosition="top" :rules="rules" class="m_t_16"></myform>
                <div class="pag pagred d_f a_i_c ">
                    <div class="line"></div>
                    所属角色
                </div>
                <div class="back">
                    <el-checkbox-group v-model="model.empRoleIds">
                        <el-checkbox :label="item.roleName" :value="item.id"  v-for="item in options.roleId" />
                    </el-checkbox-group>
                </div>
                <div class="pag d_f a_i_c m_t_20" v-if="isBiz==1">
                    <div class="line"></div>
                    其他部门查看权限
                </div>
                <div class="back" v-if="isBiz==1">
                    <el-checkbox-group v-model="model.otherDeptIds">
                        <el-checkbox :label="item.name" :value="item.id" v-for="item in dept" />
                    </el-checkbox-group>
                </div>
                <div class="pag  d_f a_i_c m_t_20">
                    <div class="line"></div>
                    用户标签
                </div>
                <div class="back">
                    <el-checkbox-group v-model="model.tagIds">
                        <el-checkbox :label="item.name" :value="item.id" v-for="item in options.usetTag" />
                    </el-checkbox-group>
                </div>
            </div>
            <div class="d_f j_c_c m_t_20">
                <el-button type="primary" @click="save" v-myRepeat>保存</el-button>
                <el-button @click="handleClose">取消</el-button>
            </div>
        </el-drawer>
        <el-drawer v-model="detailShow" title="用户详情" size="500px" direction="rtl" :before-close="handleCloseDetail">
            <div class="userForm">
                <div class="pag d_f a_i_c ">
                    <div class="line"></div>
                    用户信息
                </div>
                <div class="back">
                    <div class="d_f j_c_s_b">
                        <div class="width">姓名：{{ model.name }}</div>
                        <div class="width">手机号：{{ model.mobile }}</div>
                    </div>
                    <div class="d_f j_c_s_b m_t_10">
                        <div class="width">邮箱：{{ model.email }}</div>
                        <div class="width">所属部门：{{ deptName }}</div>
                    </div>
                </div>
                <div class="pag d_f a_i_c m_t_20">
                    <div class="line"></div>
                    所属角色
                </div>
                <div class="back">
                    <el-checkbox-group v-model="model.empRoleIds">
                        <el-checkbox :label="item.roleName" :disabled="true" :value="item.id" v-for="item in options.roleId" />
                    </el-checkbox-group>
                </div>
                <div class="pag d_f a_i_c m_t_20">
                    <div class="line"></div>
                    其他部门查看权限
                </div>
                <div class="back">
                    <el-checkbox-group v-model="model.otherDeptIds">
                        <el-checkbox :label="item.name" :disabled="true" :value="item.id" v-for="item in dept" />
                    </el-checkbox-group>
                </div>
                <div class="pag d_f a_i_c m_t_20">
                    <div class="line"></div>
                    用户标签
                </div>
                <div class="back">
                    <el-checkbox-group v-model="model.tagIds">
                        <el-checkbox :label="item.name" :disabled="true" :value="item.id" v-for="item in options.usetTag" />
                    </el-checkbox-group>
                </div>
            </div>
            <div class="d_f j_c_c m_t_20">
                <el-button type="primary" @click="openEdit">编辑</el-button>
                <el-button @click="handleCloseDetail">取消</el-button>
            </div>
        </el-drawer>
    </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, onBeforeMount, ref } from 'vue'
import { copy } from '../../../../utils/date'
import { Message } from '../../../../utils/resetMessage'
import { Search, Plus } from '@element-plus/icons-vue'
import { authorityAccountType } from '../../../../type/system'
import { ElMessageBox } from 'element-plus'
import { PHONE_REG } from '../../../../utils/regular'
import { roleList, deptList, empAdd, empUpdate, empDel, empGetById, empResetPwd, empStatus } from '../../../../api/system/authority'
import { dictDetail } from '../../../../api/login'
const values = {
    findKey: '',//员工姓名/手机号
    status: '',//0-正常，1-禁用
    deptId: null,//部门ID
    roleId: null,//角色ID
}
const model = {
    id: '',
    name: '',//员工姓名
    mobile: '',//手机号
    status: 0,//0-正常，1-禁用
    email: '',//邮箱
    deptId: '',//部门ID
    otherDeptIds: [],//其他部门
    tagIds: [],//用户标签
    empRoleIds: [],//员工角色编码列表
}
export default defineComponent({
    name: '',
    setup() {
        const data: authorityAccountType = reactive({
            fields: [
                {
                    label: "用户",
                    prop: 'findKey',
                    placeholder: '请输入姓名/手机号',
                    type: 'input',
                    labelWidth: '40px'
                },
                {
                    bindLabel: 'name',
                    bindValue: 'id',
                    label: "部门",
                    prop: 'deptId',
                    placeholder: '请选择部门',
                    type: 'select',
                    labelWidth: '50px'
                },
                {
                    label: "角色",
                    prop: 'roleId',
                    placeholder: '请选择角色',
                    type: 'select',
                    bindLabel: 'roleName',
                    bindValue: 'id',
                    labelWidth: '50px'
                },
                {
                    label: "账户状态",
                    prop: 'status',
                    placeholder: '请选择状态',
                    type: 'select',
                    bindLabel: 'name',
                    bindValue: 'id',
                    labelWidth: '70px'
                },
                {
                    prop: 'button',
                    labelWidth: '60px'
                }
            ],
            values: copy(values),
            options: {
                status: [
                    {
                        name: '正常',
                        id: '0',
                    },
                    {
                        name: '禁用',
                        id: '1',
                    },
                ],
                deptId: [],
                roleId: [],
                usetTag: []
            },
            tableFields: [
                {
                    label: '部门',
                    prop: 'deptName',
                },
                {
                    label: '姓名',
                    prop: 'name',
                },
                {
                    label: '手机号',
                    prop: 'mobile',
                },
                {
                    label: '邮箱',
                    prop: 'email',
                },
                {
                    label: '角色',
                    prop: 'empRoleName',
                },
                {
                    label: '账户状态',
                    prop: 'status',
                },
            ],
            show: false,
            title: '新建用户',
            model: copy(model),
            addFields: [
                {
                    label: "姓名",
                    prop: 'name',
                    placeholder: '请输入姓名',
                    type: 'input',
                    max:32
                },
                {
                    label: "电话",
                    prop: 'mobile',
                    placeholder: '请输入电话号码',
                    type: 'input',
                },
                {
                    label: "邮箱",
                    prop: 'email',
                    placeholder: '请输入邮箱',
                    type: 'input',
                },
                {
                    label: "所属部门",
                    prop: 'deptId',
                    placeholder: '请选择所属部门',
                    type: 'select',
                    bindLabel: 'name',
                    bindValue: 'id',
                },
            ],
            rules: {
                name: [
                    {
                        required: true,
                        message: '请输入姓名',
                        trigger: 'blur',
                    },
                ],
                mobile: [
                    {
                        required: true,
                        message: '请输入电话号码',
                        trigger: 'blur',
                    },
                    { pattern: PHONE_REG, message: '手机号格式不正确' }
                ],
                email: [
                    {
                        required: true,
                        message: '请输入邮箱地址',
                        trigger: 'blur',
                    },
                    {
                        type: 'email',
                        message: '请输入正确的邮箱地址',
                        trigger: ['blur', 'change'],
                    },
                ],
                deptId: [
                    {
                        required: true,
                        message: '请选择所属部门',
                        trigger: 'change',
                    },
                ],
            },
            dept: [],
            detailShow: false,
            deptName: '',
            array: [],
            isBiz:0
        })
        const tableRef = ref()//获取表格实例
        const ruleFrom = ref()//获取表单实例
        onBeforeMount(() => {
            methods.getData()
        })
        const methods = {
            //表格数据重置
            resetting() {
                data.values = copy(values)
                tableRef.value.resettingTable(data.values)
            },
            //列表根据筛选条件搜索
            searchFor() {
                tableRef.value.handleCurrentChange(1)
            },
            getData() {
                //获取所有角色
                roleList({}).then((res: any) => {
                    data.options.roleId = res.filter((item: any) => {
                        return item.deleted == 0
                    })
                })
                //获取所有部门
                deptList({}).then((res: any) => {
                    data.options.deptId = data.array = data.dept=res

                    // data.array = data.dept = res.filter((item: any) => {
                    //     return item.deleted == 0 
                    // })
                })
                //添加编辑用户时获取用户标签，从字典取
                dictDetail({ id: 'USER_TAG' }).then((res: any) => {
                    data.options.usetTag = res
                })
            },
            //用户的启用跟停用
            changeSwitch(id: string | number, status: number | string) {
                if (!id) return
                empStatus({ id: id, status: status }).then(() => {
                    Message({ type: 'success', message: '操作成功' })
                })
            },
            //关闭弹窗
            handleClose() {
                ElMessageBox.confirm(
                    '当前信息将不再保存?',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                )
                    .then(() => {
                        ruleFrom.value.resetFields()//重置表单
                        data.show = false
                        data.model = copy(model)
                    })
            },
            //添加用户并打开弹窗
            adduser() {
                data.title = '新增用户'
                data.show = true
            },
            //新增用户跟修改用户
            save() {
                ruleFrom.value.verification().then(() => {
                    if(data.model.empRoleIds.length==0)return  Message({ type: 'error', message: '请选择所属角色' })
                    if (!data.model.id) {
                        empAdd(data.model).then(() => {
                            Message({ type: 'success', message: '添加成功' })
                            tableRef.value.handleCurrentChange(1)//添加表格之后重新获取表格
                            data.show = false//关闭弹窗
                            ruleFrom.value.resetFields()//重置表单
                            data.model = copy(model)//重置表单绑定数据
                        })
                    } else {
                        empUpdate(data.model).then(() => {
                            Message({ type: 'success', message: '修改成功' })
                            tableRef.value.handleCurrentChange(1)//添加表格之后重新获取表格
                            data.show = false//关闭弹窗
                            ruleFrom.value.resetFields()//重置表单
                            data.model = copy(model)//重置表单绑定数据
                        })
                    }
                })
            },
            //表单选择部门回调，并过滤其他部门中的当前部门
            handleSelect(prop: string) {
                if (prop == 'deptId') {
                    data.dept.map((item:any)=>{
                     if(item.id == data.model.deptId){
                      data.isBiz=item.isBiz
                     }
                    })
                    data.dept = data.array.filter((item:any) => {
                        return item.id != data.model.deptId
                    })
                    data.model.otherDeptIds = []
                }
            },
            //从列表中删除用户
            deleteOut(id: string | string) {
                ElMessageBox.confirm(
                    '是否删除当前用户?',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'error',
                    }
                )
                    .then(() => {
                        empDel({ id: id }).then(() => {
                            Message({ type: 'success', message: '删除成功' })
                            tableRef.value.handleCurrentChange(1)//添加表格之后重新获取表格
                        })
                    })
            },
            //编辑用户信息并回显表单数据
            edit(row: any) {
                empGetById({ id: row.id }).then((res:any) => {
                    data.title = '编辑用户'
                    methods.copyData(res)
                    data.show = true
                   
                })
            },
            //重置用户密码
            resetPassword(row: any) {
                let message = `确认重置“${row.name}”的密码为手机号后6位？`
                ElMessageBox.confirm(
                    message,
                    '重置密码',
                    {
                        confirmButtonText: '确认重置',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                )
                    .then(() => {
                        empResetPwd({ id: row.id }).then(() => {
                            Message({ type: 'success', message: '重置成功' })
                        })
                    })
            },
            copyData(res: any) {
                data.model.name = res.name
                data.model.id = res.id
                data.model.mobile = res.mobile
                data.model.email = res.email
                data.model.status = res.status
                data.model.deptId = res.deptId
                data.model.otherDeptIds = res.otherDeptIds || []
                data.model.tagIds = res.tagIds || []
                data.model.empRoleIds = res.empRoleList || []
                // data.dept = data.options.deptId.filter((item) => {
                //     return item.id != data.model.deptId
                // })
                methods.handleSelect('deptId')
            },
            //查看用户详情
            detail(row: any) {
                empGetById({ id: row.id }).then((res: any) => {
                    data.deptName = row.deptName
                    methods.copyData(res)
                    data.detailShow = true
                })
            },
            //打开编辑弹窗
            openEdit() {
                data.title = '编辑用户'
                data.detailShow = false
                data.show = true
            },
            //关闭查看弹窗
            handleCloseDetail() {
                data.detailShow = false
                data.model = copy(model)
            }
        }
        return {
            ...toRefs(data),
            ...methods, Search, Plus,
            tableRef, ruleFrom
        }
    }
})
</script>
<style scoped lang='scss'>
.box {
  width: calc(100% - 64px);
  background: #fff;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  height: 70px;
  padding: 10px 32px;
  margin-top: 10px;
}

.mytable {
  overflow-y: auto;
  width: calc(100% - 64px);
  background: #fff;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 10px 32px;
  height: calc(100% - 125px);
}

.pag {
    background: rgba(24, 120, 255, 0.04);
    width: calc(100% - 48px);
    padding: 12px 24px;
    border-radius: 6px 6px 0px 0px;

    .line {
        width: 4px;
        height: 16px;
        background: #1878FF;
        margin-right: 8px;
    }
}
.pagred::before{
    color: var(--el-color-danger);
    content: "*";
    margin-right: 4px;
}
.back {
    background: rgba(24, 120, 255, 0.04);
    width: calc(100% - 48px);
    padding: 12px 24px;
    margin-top: 12px;
}

.width {
    width: 50%;
    text-align: left;
    font-size: 14px;
}
</style>
<style lang="scss">
.userForm {
    height: calc(100% - 70px);
    overflow-y: auto;
    .el-form {
        justify-content: space-between;
    }

    .el-form-item {
        width: 45%;
        margin-right: 0px !important;

        .el-input,
        .el-select {
            width: 100% !important;
        }
    }
}
</style>